#ifndef STREAMRECORDER_H
#define STREAMRECORDER_H
#include <atomic>
#include <memory>
#include <QDateTime>
#include <QDebug>
#include <QMutex>
#include <QProcess>
#include <QTimer>

class StreamRecorder : public QObject
{
    Q_OBJECT
public:
    struct Config
    {
        QString inputUrl;
        QString outputFile;
        int maxBandwidth;
        bool hwAccel;
        QStringList customArgs;
        int maxRetries = 3;
        int retryInterval = 5000;
        QString segmentPath; // 新增：分段文件保存路径
    };

    StreamRecorder(const Config& config, QObject* parent = nullptr);
    ~StreamRecorder();

    void start();
    void stop();
    void adjustEncodingParams(const QStringList& newParams);

signals:
    void progressUpdated(double progress, qint64 elapsed);
    void qosMetrics(double fps, double bitrate);
    void bandwidthAdjusted(int newBitrate);
    void statusMessage(const QString& message);
    void errorOccurred(const QString& error);
    void outputValidated(bool isValid);

private slots:
    void parseOutput();
    void handleProcessExit(int exitCode, QProcess::ExitStatus exitStatus);
    void calculateQoSMetrics();
    void adjustBandwidth();
    void updateBitrateParams(int newBitrate);
    void restartIfNeeded();
    void handleNetworkError();
    void quickRecover();
    void sendFFmpegCommand(const QString& cmd);
    void reconnectStream();
    void validateOutput();
    void scheduleRetry();

private:
    Config m_config;
    std::unique_ptr<QProcess> m_process;
    std::unique_ptr<QTimer> m_qosTimer;
    std::unique_ptr<QTimer> m_restartTimer;
    QMutex m_mutex;
    QMutex m_paramMutex;
    QStringList m_customArgs;
    QStringList m_currentParams;
    std::atomic<bool> m_terminateRequested { false };
    std::atomic_flag m_active = ATOMIC_FLAG_INIT;
    int m_currentRetry = 0;
    int m_maxRetries;
    int m_retryInterval;
    int m_processedFrames = 0;
    qint64 m_totalDuration = 0;
    QDateTime m_startTime;
    QList<double> m_fpsHistory;
    QList<double> m_bitrateHistory;
    double m_currentFps = 0;
    double m_currentBitrate = 0;
    int m_networkErrors = 0;
    bool m_needsRestart = false;
    int m_currentSegment = 0; // 新增：当前分段编号
    qint64 m_lastProcessedFrame = 0; // 新增：最后处理的帧数

    void initFFmpegProcess();
    void initQoSTimers();
    void setupHardwareAcceleration();
    void startConversion();
    void startConversionFromFrame(qint64 frame); // 新增：从指定帧开始转换
    void processLine(const QByteArray& line);
    double calculateAverage(const QList<double>& list);
    void cleanup();
    void stopFFmpegGracefully(); // 新增：优雅地停止 FFmpeg 进程
};

#endif // STREAMRECORDER_H
